package com.thatvn.diemtinvietnam;
import java.util.ArrayList;
import java.util.HashMap;

import com.thatvn.diemtinvietnam.R;

import android.app.Activity;
import android.content.Context;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.CheckedTextView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.content.Intent;
import android.widget.RelativeLayout;

public class MyExpandableAdapter extends BaseExpandableListAdapter {
	
	private Activity activity;
	private ArrayList<Object> childtems;
	private LayoutInflater inflater;
	private ArrayList<HashMap<String, String>> parentItems, child;
	private HashMap<String, String> parentNews;
	public ImageLoader imageLoader;
	public Typeface typefaceTitle,typefaceInfo;
	public Context context;
	private static final int[] EMPTY_STATE_SET = {};
    private static final int[] GROUP_EXPANDED_STATE_SET =
            {android.R.attr.state_expanded};
    private static final int[][] GROUP_STATE_SETS = {
         EMPTY_STATE_SET, // 0
         GROUP_EXPANDED_STATE_SET // 1
	};
    
	public MyExpandableAdapter(ArrayList<HashMap<String, String>> parents, ArrayList<Object> childern,Activity a,Context context) {
		this.parentItems = parents;
		this.childtems = childern;
		this.context=context;
		activity=a;
		imageLoader=new ImageLoader(activity.getApplicationContext());
		typefaceTitle=Typeface.createFromAsset(context.getAssets(),"fonts/Roboto-Bold.ttf");
	    typefaceInfo=Typeface.createFromAsset(context.getAssets(),"fonts/Roboto-Regular.ttf");
	}

	public void setInflater(LayoutInflater inflater, Activity activity) {
		this.inflater = inflater;
		this.activity = activity;
	}

	
	@Override
	public View getChildView(int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
		//Log.e("BBBBBBBBBBBBBBBBgroupPosition="+groupPosition, "childPosition="+childPosition);
//		if (isLastChild && childPosition==0){
//			//Load tin chinh
////			titleRelated = (TextView) convertView.findViewById(R.id.titleRelated);
////	        sourceRelated = (TextView) convertView.findViewById(R.id.sourceRelated);
////			thumb_image=(ImageView) convertView.findViewById(R.id.list_image_related);
//			Log.e("getChildrenCountgetChildrenCountgetChildrenCount", String.valueOf(getChildrenCount(groupPosition)));
//			//RelativeLayout rl=(RelativeLayout) convertView.findViewById(R.id.rltLayout);
//			//rl.setVisibility(View.GONE);
//			Intent vi = new Intent(activity, viewWeb.class);
//			vi.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//			//Intent vi = new Intent(Intent.ACTION_VIEW, Uri.parse(link));
//			vi.putExtra("link", this.parentItems.get(groupPosition).get(MainActivity.KEY_LINK));			
//			vi.putExtra("id", this.parentItems.get(groupPosition).get(MainActivity.KEY_ID));
//			//vi.setData(Uri.parse(link));
//			context.startActivity(vi);
//			if (convertView == null) {				
//					convertView = inflater.inflate(R.layout.list_row_child_emty, null);				
//			}
//			return convertView;
//		}
		TextView titleRelated = null,sourceRelated=null;
		ImageView thumb_image=null;
//		if (groupPosition>=childtems.size()){
//			Log.e("BBBBBBBBBBBBBBBB", "Not FOUNDDDDDDDDDDDDDDDDDD");
//			return null;
//		}
		child = (ArrayList<HashMap<String,String>>) this.childtems.get(groupPosition);

		
		if (convertView == null) {			
				convertView = inflater.inflate(R.layout.list_row_child, null);
		}
		HashMap<String, String> news = new HashMap<String, String>();
		
		//if (childPosition<child.size()){
	        news = child.get(childPosition);	        
	        titleRelated = (TextView) convertView.findViewById(R.id.titleRelated);	        
	        titleRelated.setText(Html.fromHtml(news.get(MainActivity.KEY_NAMERELATED)));
	        sourceRelated = (TextView) convertView.findViewById(R.id.sourceRelated);	        
	        sourceRelated.setText(Utils.smoothDomain(news.get(MainActivity.KEY_SOURCERELATED)));
			thumb_image=(ImageView) convertView.findViewById(R.id.list_image_related);
			//Log.e("aaaaaaaaaaaaaaaaaaa,child size="+child.size(), String.valueOf(news.get(MainActivity.KEY_NAMERELATED)));
		//}
			if (Config.isTablet) {
				titleRelated.setTextSize(context.getResources().getDimension(R.dimen.TableTextSizeTitle));
				sourceRelated.setTextSize(context.getResources().getDimension(R.dimen.TableTextSizeNormal));	        	
	        	thumb_image.getLayoutParams().height = 120;
	        	thumb_image.getLayoutParams().width = 120;
	        }
			
			String image="";
	        try{
	        	image=news.get(MainActivity.KEY_IMAGERELATED).trim();
	        if (image.isEmpty() || image.equals("") || image.equals(null)) 
	        	{
	        		//Log.e("getImage", String.valueOf(news.get(MainActivity.KEY_SOURCE)));
	        		image=Utils.getDomainImage(news.get(MainActivity.KEY_SOURCERELATED));
	        		//Log.e("image=", String.valueOf(image));
	        	}
	        }catch(Exception ex){
	        		image=Utils.getDomainImage(news.get(MainActivity.KEY_SOURCERELATED));
	        }
	        imageLoader.DisplayImage(image, thumb_image);
//		    convertView.setOnClickListener(new OnClickListener() {			
//			@Override
//			public void onClick(View view) {
//				Log.e("bbbb", "vao 1:"+child.get(childPosition).get(MainActivity.KEY_NAMERELATED));
////				Toast.makeText(activity, childPosition,
////						Toast.LENGTH_SHORT).show();
////				Intent vi = new Intent(activity, viewWeb.class);
////				vi.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
////				//Intent vi = new Intent(Intent.ACTION_VIEW, Uri.parse(link));
////				vi.putExtra("link", child.get(childPosition).get(MainActivity.KEY_LINKRELATED));			
////				vi.putExtra("id", child.get(childPosition).get(MainActivity.KEY_IDRELATED));
////				//vi.setData(Uri.parse(link));
////				context.startActivity(vi);
//			}
//		});
		
		return convertView;
	}
//	public void viewWeb(Intent vi){
//		startActivity(vi);
//	}
	@Override
	public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
		View vi=convertView;
		if (convertView == null) {
			vi = inflater.inflate(R.layout.list_row, null);
		}
		//Log.e("getChildrenCountgetChildrenCountgetChildrenCount", String.valueOf(getChildrenCount(groupPosition)));
		View ind = vi.findViewById( R.id.explist_indicator);
		if( ind != null ) {
			ImageView indicator = (ImageView)ind;
			if( getChildrenCount(groupPosition) <= 0 ) {
				indicator.setVisibility( View.INVISIBLE );
			} else {
				indicator.setVisibility( View.VISIBLE );
				int stateSetIndex = ( isExpanded ? 1 : 0);
				Drawable drawable = indicator.getDrawable();
				drawable.setState(GROUP_STATE_SETS[stateSetIndex]);
			}
		}
		
//		((CheckedTextView) convertView).setText(parentItems.get(groupPosition));
//		((CheckedTextView) convertView).setChecked(isExpanded);
		 TextView title = (TextView)vi.findViewById(R.id.title); // title
	        TextView source = (TextView)vi.findViewById(R.id.source); // source
	        TextView date = (TextView)vi.findViewById(R.id.date); // date
	        TextView no = (TextView)vi.findViewById(R.id.no); // no
	        TextView ranking = (TextView)vi.findViewById(R.id.ranking); // ranking
	        ImageView thumb_image=(ImageView)vi.findViewById(R.id.list_image); // thumb image
	        TextView catname = (TextView)vi.findViewById(R.id.catname);
	        no.setVisibility(View.GONE);
	        ranking.setVisibility(View.GONE);
	        source.setVisibility(View.GONE);
	        if (Config.isTablet) {
	        	title.setTextSize(context.getResources().getDimension(R.dimen.TableTextSizeTitle));
	        	source.setTextSize(context.getResources().getDimension(R.dimen.TableTextSizeNormal));
	        	date.setTextSize(context.getResources().getDimension(R.dimen.TableTextSizeNormal));
	        	no.setTextSize(context.getResources().getDimension(R.dimen.TableTextSizeNormal));
	        	ranking.setTextSize(context.getResources().getDimension(R.dimen.TableTextSizeNormal));
	        	catname.setTextSize(context.getResources().getDimension(R.dimen.TableTextSizeNormal));	
	        	thumb_image.getLayoutParams().height = 160;
	        	thumb_image.getLayoutParams().width = 240;
	        }
	        
	        HashMap<String, String> news = new HashMap<String, String>();
	        news = this.parentItems.get(groupPosition);
	        
//	        if (groupPosition<=1 || Integer.parseInt(news.get(MainActivity.KEY_RANKING))>=500){
//	        	thumb_image.getLayoutParams().height = 120;
//	        	thumb_image.getLayoutParams().width = 120;	        	
//	        }
	        //AssetManager am=getContext(;
	        // Setting all values in listview
	        
	        title.setTypeface(typefaceTitle);
	        source.setTypeface(typefaceInfo);
	        date.setTypeface(typefaceInfo);
	        catname.setTypeface(typefaceInfo);
	        no.setTypeface(typefaceTitle);
	        ranking.setTypeface(typefaceTitle);
	        title.setText(Html.fromHtml(news.get(MainActivity.KEY_TITLE)));	        
	        //if (Config.typeLoad==0){
	        	catname.setText(Utils.smoothDomain(news.get(MainActivity.KEY_SOURCE)));
	        //}else{
	        	//catname.setText(" | "+Utils.smoothDomain(news.get(MainActivity.KEY_SOURCE)));        
	        //}
	        //if (Config.typeView==1) catname.setText("");
	        if (Config.typeLoad==0){
	        	source.setText(Utils.smoothDomain(news.get(MainActivity.KEY_SOURCE))+" | ");
	        }else{
	        	source.setText("");
	        }
	        if (Config.typeView==1) {
	        	source.setText("");
	        	
	        }
	        int hourDiff=Integer.parseInt(news.get(MainActivity.KEY_TIMEDIFF));
	        String timeDiff="";
	        if (hourDiff<=5){
	        	timeDiff="5 phút  trước";
	        }else{
	        	if (hourDiff>=60){
	        		hourDiff=hourDiff/60;
	        		if (hourDiff==1) {
	        			timeDiff=" 1 giờ trước.";
	        		}
	        		else{
	        			//hourDiff=hourDiff/24;
	        			if (hourDiff>=24){
	        				hourDiff=hourDiff/24;
	        				//if (hourDiff==1) 
	        					timeDiff="hôm qua";
	        				//else
	        					//timeDiff=hourDiff+" ngày trước";
	        			}else{
	        				timeDiff=hourDiff+" giờ trước";
	        			}
	        		}
	        	} else {
	        		timeDiff=hourDiff+" phút trước";
	        	}
	        }	               
	        date.setText(timeDiff);
	        if (Config.typeView==1) date.setText(news.get("date"));
	        no.setText(String.valueOf(groupPosition+1));
	        ranking.setText(news.get(MainActivity.KEY_RANKING));
	        if (Config.typeView==1) 
	        {
	        		ranking.setText("");
	        		no.setText("");
	        }
	        //Log.e("getView", String.valueOf(totalNumber));
	        String image="";
	        try{
	        	image=news.get(MainActivity.KEY_IMAGE).trim();
	        if (image.isEmpty() || image.equals("") || image.equals(null)) 
	        	{
	        		//Log.e("getImage", String.valueOf(news.get(MainActivity.KEY_SOURCE)));
	        		image=Utils.getDomainImage(news.get(MainActivity.KEY_SOURCE));
	        		//Log.e("image=", String.valueOf(image));
	        	}
	        }catch(Exception ex){
	        		image=Utils.getDomainImage(news.get(MainActivity.KEY_SOURCE));
	        }
	        imageLoader.DisplayImage(image, thumb_image);
//	        parentNews= new HashMap<String, String>();
//	        parentNews=news;
//	        //if( getChildrenCount(groupPosition) <= 0 ) {
//		        vi.setOnClickListener(new OnClickListener() {			
//					@Override
//					public void onClick(View view) {
//						Log.e("bbbb", "vao 1:"+parentNews.get(MainActivity.KEY_TITLE));
//	//					Toast.makeText(activity, childPosition,
//	//							Toast.LENGTH_SHORT).show();
//						Intent viIT = new Intent(activity, viewWeb.class);
//						viIT.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//						//Intent vi = new Intent(Intent.ACTION_VIEW, Uri.parse(link));
//						viIT.putExtra("link", parentNews.get(MainActivity.KEY_LINK));			
//						viIT.putExtra("id", parentNews.get(MainActivity.KEY_ID));
//						//vi.setData(Uri.parse(link));
//						context.startActivity(viIT);
//					}
//		        });
	        //}
		return vi;
	}

	@Override
	public Object getChild(int groupPosition, int childPosition) {
		return null;
	}

	@Override
	public long getChildId(int groupPosition, int childPosition) {
		return 0;
	}

	@Override
	public int getChildrenCount(int groupPosition) {
		try{
			child = (ArrayList<HashMap<String,String>>) childtems.get(groupPosition);
			if (child.get(0).isEmpty() || child.get(0).get(MainActivity.KEY_NAMERELATED).equals("")) return 0;
			return child.size();
		}catch(Exception ex){
			return 0;
		}
		//return childtems.get(groupPosition)..size();
		
	}

	@Override
	public Object getGroup(int groupPosition) {
		return null;
	}

	@Override
	public int getGroupCount() {
		return parentItems.size();
	}

	@Override
	public void onGroupCollapsed(int groupPosition) {
		super.onGroupCollapsed(groupPosition);
	}

	@Override
	public void onGroupExpanded(int groupPosition) {
		super.onGroupExpanded(groupPosition);
	}

	@Override
	public long getGroupId(int groupPosition) {
		return 0;
	}

	

	@Override
	public boolean hasStableIds() {
		return false;
	}

	@Override
	public boolean isChildSelectable(int groupPosition, int childPosition) {
		return true;
	}

}
